package com.morn.weibo.http;

import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.james.mime4j.util.CharsetUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.morn.weibo.exception.WeiboException;
import com.morn.weibo.http.CountingMultipartEntity.ProgressListener;
import com.morn.weibo.http.image.ImageTool;
import com.morn.weibo.types.AccountNotification;
import com.morn.weibo.types.Conversation;
import com.morn.weibo.types.Message;
import com.morn.weibo.types.Status;
import com.morn.weibo.types.Trends;
import com.morn.weibo.types.User;
import com.morn.weibo.utils.UrlStr;

import android.content.Context;
import android.util.Log;
import android.widget.ImageView;

public class Fanfou extends FanfouSupport {

	private ImageTool imageTool;

	public Fanfou(Context context) {
		super(context);
		imageTool = new ImageTool(httpClient, context);
	}

	public List<Status> getPhotoStatus(String sinceId, String maxId,
			String page, String userId) throws Exception {
		String str = doHttpGet(UrlStr.PHOTOS_USER_TIMELINE,
				new BasicNameValuePair("format", "html"),
				new BasicNameValuePair("since_id", sinceId),
				new BasicNameValuePair("max_id", maxId),
				new BasicNameValuePair("page", page), new BasicNameValuePair(
						"mode", "lite"), new BasicNameValuePair("id", userId));
		return Status.getStatusList(new JSONArray(str));
	}

	public List<Status> getHomeStatusList(String sinceId, String maxId,
			String page, String userId) throws JSONException, WeiboException {
		String str = doHttpGet(UrlStr.STATUSES_HOME_TIMELINE,
				new BasicNameValuePair("format", "html"),
				new BasicNameValuePair("since_id", sinceId),
				new BasicNameValuePair("max_id", maxId),
				new BasicNameValuePair("page", page), new BasicNameValuePair(
						"mode", "lite"), new BasicNameValuePair("id", userId));
		return Status.getStatusList(new JSONArray(str));
	}

	public List<Status> getRepliesStatusList(String sinceId, String maxId,
			String page, String userId) throws WeiboException, JSONException {
		String str = doHttpGet(UrlStr.STATUSES_REPLIES, new BasicNameValuePair(
				"format", "html"), new BasicNameValuePair("since_id", sinceId),
				new BasicNameValuePair("max_id", maxId),
				new BasicNameValuePair("page", page), new BasicNameValuePair(
						"mode", "lite"), new BasicNameValuePair("id", userId));
		return Status.getStatusList(new JSONArray(str));
	}

	public List<Status> getUserStatusList(String userId, String sinceId,
			String maxId, String page) throws WeiboException, JSONException {
		String str = doHttpGet(UrlStr.STATUSES_USER_TIMELINE,
				new BasicNameValuePair("format", "html"),
				new BasicNameValuePair("since_id", sinceId),
				new BasicNameValuePair("max_id", maxId),
				new BasicNameValuePair("page", page), new BasicNameValuePair(
						"mode", "lite"), new BasicNameValuePair("id", userId));
		return Status.getStatusList(new JSONArray(str));
	}

	public List<Status> getPublicStatusList(String sinceId, String maxId)
			throws WeiboException, JSONException {
		String str = doHttpGet(UrlStr.STATUSES_PUBLIC_TIMELINE,
				new BasicNameValuePair("format", "html"),
				new BasicNameValuePair("since_id", sinceId),
				new BasicNameValuePair("max_id", maxId),
				new BasicNameValuePair("mode", "lite"));
		return Status.getStatusList(new JSONArray(str));
	}

	public List<Status> getContextStatusList(String id) throws WeiboException,
			JSONException {
		String str = doHttpGet(UrlStr.STATUSES_CONTEXT_TIMELINE,
				new BasicNameValuePair("format", "html"),
				new BasicNameValuePair("id", id), new BasicNameValuePair(
						"mode", "lite"));
		return Status.getStatusList(new JSONArray(str));
	}

	public Status getStatus(String statusId) throws WeiboException,
			JSONException {
		String str = doHttpGet(UrlStr.STATUSES_SHOW, new BasicNameValuePair(
				"format", "html"), new BasicNameValuePair("id", statusId),
				new BasicNameValuePair("mode", "lite"));
		return new Status(new JSONObject(str));
	}

	public List<Status> getFavorites(String userId, String page)
			throws WeiboException, JSONException {
		String str = doHttpGet(UrlStr.FAVORITES, new BasicNameValuePair("id",
				userId), new BasicNameValuePair("page", page),
				new BasicNameValuePair("format", "html"),
				new BasicNameValuePair("mode", "lite"));
		return Status.getStatusList(new JSONArray(str));
	}

	// ------------------------------------------

	public String updateStatus(String str, String reStatusId, String reUserId,
			String repostId, String location) throws WeiboException {
		return doHttpPost(UrlStr.STATUSES_POST_UPDATE, new BasicNameValuePair(
				"status", str), new BasicNameValuePair("in_reply_to_status_id",
				reStatusId), new BasicNameValuePair("in_reply_to_user_id",
				reUserId),
				new BasicNameValuePair("repost_status_id", repostId),
				new BasicNameValuePair("source", null), new BasicNameValuePair(
						"location", location));
	}

	public String deleteStatus(String idStr) throws WeiboException {
		return doHttpPost(UrlStr.STATUSES_POST_DESTROY, new BasicNameValuePair(
				"id", idStr), new BasicNameValuePair("mode", "lite"),
				new BasicNameValuePair("format", "html"));
	}

	// ----

	public String uploadStatus(ContentBody photo, String description,
			ProgressListener progressListener) throws WeiboException {
		String urlStr = BASEURL + UrlStr.STATUSES_POST_PHOTOS;
		HttpPost httpPost = new HttpPost(urlStr);
		String returnStr = null;
		CountingMultipartEntity reqEntity = new CountingMultipartEntity(
				progressListener);

		reqEntity.addPart("photo", photo);
		try {
			if (description != null && description.length() > 0)
				reqEntity.addPart("status", new StringBody(description,
						CharsetUtil.getCharset("UTF-8")));
			httpPost.setEntity(reqEntity);
			HttpResponse response = httpClient.execute(httpPost);
			HttpEntity resEntity = response.getEntity();
			returnStr = EntityUtils.toString(resEntity);
		} catch (Exception e) {
			httpPost.abort();
			e.printStackTrace();
			throw new WeiboException(e.getMessage());

		}
		return returnStr;
	}

	public List<Status> searchStatus(String q, String maxId)
			throws WeiboException, JSONException {
		String str = doHttpGet(UrlStr.SEARCH_STATUSES, new BasicNameValuePair(
				"q", q), new BasicNameValuePair("format", "html"),
				new BasicNameValuePair("mode", "lite"), new BasicNameValuePair(
						"max_id", maxId));
		return Status.getStatusList(new JSONArray(str));
	}

	public List<User> searchUser(String q, String maxId) throws WeiboException,
			JSONException {
		String str = doHttpGet(UrlStr.SEARCH_USERS, new BasicNameValuePair("q",
				q), new BasicNameValuePair("format", "html"),
				new BasicNameValuePair("mode", "lite"), new BasicNameValuePair(
						"max_id", maxId));
		// TODO total_number: 86
		return User.getUserList(new JSONArray(str));
	}

	public List<User> getFriends(String userId, String page)
			throws WeiboException, JSONException {
		String str = doHttpGet(UrlStr.STATUSES_FRIENDS, new BasicNameValuePair(
				"id", userId), new BasicNameValuePair("page", page));
		return User.getUserList(new JSONArray(str));
	}

	public List<User> getFollows(String userId, String page)
			throws WeiboException, JSONException {
		String str = doHttpGet(UrlStr.STATUSES_FOLLOWERS,
				new BasicNameValuePair("id", userId), new BasicNameValuePair(
						"page", page), new BasicNameValuePair("mode", "lite"));
		return User.getUserList(new JSONArray(str));
	}

	public User getUser(String userId) throws WeiboException, JSONException {
		String str = doHttpGet(UrlStr.USERS_SHOW, new BasicNameValuePair("id",
				userId), new BasicNameValuePair("mode", "lite"));
		return new User(new JSONObject(str));
	}

	public List<Message> getReceivedMessage(String maxId)
			throws WeiboException, JSONException {
		String str = doHttpGet(UrlStr.MESSAGES_DIRECT, new BasicNameValuePair(
				"max_id", maxId));
		return Message.getMessageList(new JSONArray(str));
	}

	public List<Message> getSendMessage(String maxId) throws WeiboException,
			JSONException {
		String str = doHttpGet(UrlStr.MESSAGES_DIRECT_SENT,
				new BasicNameValuePair("max_id", maxId));
		return Message.getMessageList(new JSONArray(str));
	}

	public Message sendMessage(String userId, String text, String replyId)
			throws WeiboException, JSONException {
		String str = doHttpPost(UrlStr.MESSAGES_NEW, new BasicNameValuePair(
				"user", userId), new BasicNameValuePair("text", text),
				new BasicNameValuePair("mode", "lite"), new BasicNameValuePair(
						"text", text), new BasicNameValuePair("in_reply_to_id",
						replyId));
		return new Message(new JSONObject(str));
	}

	public Message deleteMessage(String messageId) throws WeiboException,
			JSONException {
		String str = doHttpPost(UrlStr.MESSAGES_DESTROY,
				new BasicNameValuePair("id", messageId));
		return new Message(new JSONObject(str));
	}

	//
	public String createFavorites(String statusId) throws WeiboException {
		return doHttpPost(UrlStr.FAVORITES_CREATE, new BasicNameValuePair("id",
				statusId), new BasicNameValuePair("mode", "lite"));
	}

	public String deleteFavorites(String statusId) throws WeiboException {
		return doHttpPost(UrlStr.FAVORITES_DESTROY, new BasicNameValuePair(
				"id", statusId), new BasicNameValuePair("mode", "lite"));
	}

	public User createFriendships(String userId) throws WeiboException,
			JSONException {
		String str = doHttpPost(UrlStr.FRIENDSHIPS_CREATE,
				new BasicNameValuePair("id", userId), new BasicNameValuePair(
						"mode", "lite"));
		return new User(new JSONObject(str));
	}

	public User deleteFriendships(String userId) throws WeiboException,
			JSONException {
		String str = doHttpPost(UrlStr.FRIENDSHIPS_DESTROY,
				new BasicNameValuePair("id", userId), new BasicNameValuePair(
						"mode", "lite"));
		return new User(new JSONObject(str));
	}

	public boolean isFriendships(String user_a, String user_b)
			throws WeiboException {
		String str = doHttpGet(UrlStr.FRIENDSHIPS_EXISTS,
				new BasicNameValuePair("user_a", user_a),
				new BasicNameValuePair("user_b", user_b));
		return "true".equals(str);
	}

	public List<Trends> getTrendsList() throws WeiboException, JSONException {
		String str = doHttpGet(UrlStr.URL_API_TRENDS);
		return Trends.getTrendsList(new JSONObject(str));
	}

	public AccountNotification getAccountNotification() throws Exception {
		String str = doHttpGet(UrlStr.ACCOUNT_NOTIFICATION);
		return new AccountNotification(new JSONObject(str));
	}

	public List<Conversation> getConversationList(String count, String page)
			throws Exception {
		String str = doHttpGet(UrlStr.MESSAGES_CONVERSATION_LIST,
				new BasicNameValuePair("count", count), new BasicNameValuePair(
						"page", page), new BasicNameValuePair("mode", "lite"));
		Log.i("testFanfou", str);
		return Conversation.getConversationList(new JSONArray(str));
	}

	public List<Message> getConverSation(String userId, String max_id,
			String count, String page) throws Exception {
		String str = doHttpGet(UrlStr.MESSAGES_CONVERSATION,
				new BasicNameValuePair("id", userId), new BasicNameValuePair(
						"count", count), new BasicNameValuePair("max_id",
						max_id), new BasicNameValuePair("page", page),
				new BasicNameValuePair("mode", "lite"));
		return Message.getMessageList(new JSONArray(str));
	}

	public User verifyAccount() throws Exception {
		String str = doHttpGet(UrlStr.ACCOUNT_VERIFY_CREDENTIALS,
				new BasicNameValuePair("format", "html"),
				new BasicNameValuePair("mode", "lite"));
		return new User(new JSONObject(str));
	}

	public void downloadImage(String url, ImageView imageView) {
		imageTool.download(url, imageView);
	}
}
